package com.zhiqian.community.controller;

import com.zhiqian.community.entity.Comment;
import com.zhiqian.community.entity.Page;
import com.zhiqian.community.entity.User;
import com.zhiqian.community.service.CommentService;
import com.zhiqian.community.service.UserService;
import com.zhiqian.community.util.CommunityConstant;
import com.zhiqian.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {
    @Autowired
    private CommentService commentService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;

    @PostMapping("/addComment/{discussPostId}")
    public String addComment(Comment comment,@PathVariable("discussPostId") Integer discussPostId){
        comment.setUserId(hostHolder.getUser().getId());
        commentService.addComment(comment,discussPostId);
        return "redirect:/discuss/detail/"+discussPostId;
    }

    /**
     * 查询用户发布的评论
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @GetMapping("/user/{userId}")
    public String findCommentIssuedByUser(@PathVariable("userId") Integer userId, Page page, Model model){
        User target = userService.getUserById(userId);
        if (target==null){
            throw new RuntimeException("该用户不存在!");
        }
        page.setRows(commentService.selectUserCommentCount(userId));
        page.setPath("/comment/user/"+userId);
        page.setLimit(20);
        List<Map<String, Object>> comments = commentService.selectUserComments(userId, page);
        model.addAttribute("comments",comments);
        model.addAttribute("target",target);
        return "/site/my-reply";
    }
}
